package com.originskyseed.platform.task.service.impl;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.common.logger.Logger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.stereotype.Component;

import com.originskyseed.platform.common.api.util.DataUtil;
import com.originskyseed.platform.common.api.util.QueryAppUtil;
import com.originskyseed.platform.common.api.util.TimeFormatUtil;
import com.originskyseed.platform.common.utils.JsonUtils;
import com.originskyseed.platform.core.base.BasePage;
import com.originskyseed.platform.core.tenant.util.TenantCodeUtil;
import com.originskyseed.platform.core.util.bean.PrimaryKeyGeneratorUtil;
import com.originskyseed.platform.course.mapper.PaperMapper;
import com.originskyseed.platform.course.mapper.PaperRelateUserMapper;
import com.originskyseed.platform.course.model.Paper;
import com.originskyseed.platform.course.model.PaperRelateUser;
import com.originskyseed.platform.task.mapper.SpreadLimitMapper;
import com.originskyseed.platform.task.mapper.SpreadUsedMapper;
import com.originskyseed.platform.task.mapper.TaskMapper;
import com.originskyseed.platform.task.mapper.TaskRelateAssignPersonMapper;
import com.originskyseed.platform.task.mapper.TaskRelateCourseMapper;
import com.originskyseed.platform.task.mapper.TaskRelateCourseUserMapper;
import com.originskyseed.platform.task.mapper.TaskRelateMaintainUserMapper;
import com.originskyseed.platform.task.model.SpreadLimit;
import com.originskyseed.platform.task.model.SpreadUsed;
import com.originskyseed.platform.task.model.Task;
import com.originskyseed.platform.task.model.TaskRankVO;
import com.originskyseed.platform.task.model.TaskRelateAssignPerson;
import com.originskyseed.platform.task.model.TaskRelateCourse;
import com.originskyseed.platform.task.model.TaskRelateCourseUser;
import com.originskyseed.platform.task.model.TaskRelateMaintainUser;
import com.originskyseed.platform.task.model.TaskVO;
import com.originskyseed.platform.task.service.ITaskService;
import com.originskyseed.platform.user.mapper.DeptMapper;
import com.originskyseed.platform.user.mapper.ParameterConfigureMapper;
import com.originskyseed.platform.user.mapper.PlayerMapper;
import com.originskyseed.platform.user.mapper.PlayerRelateConsumeMapper;
import com.originskyseed.platform.user.mapper.UserInfoMapper;
import com.originskyseed.platform.user.model.Anchor;
import com.originskyseed.platform.user.model.Dept;
import com.originskyseed.platform.user.model.ParameterConfigure;
import com.originskyseed.platform.user.model.Player;
import com.originskyseed.platform.user.model.PlayerRelateConsume;
import com.originskyseed.platform.user.model.UserInfo;

/**
 * 任务表Service接口实现类（OSI_TASK）
 *
 * @author wlj
 */
@DubboService
@Component("taskService")
public class TaskServiceImpl implements ITaskService {

	private static final Logger logger = LoggerFactory.getLogger(TaskServiceImpl.class);

	@Resource
	private TaskMapper taskMapper;

	@Resource
	private SpreadLimitMapper spreadLimitMapper;

	@Resource
	private TaskRelateMaintainUserMapper taskRelateMaintainUserMapper;

	@Resource
	private TaskRelateCourseMapper taskRelateCourseMapper;

	@Resource
	private TaskRelateCourseUserMapper taskRelateCourseUserMapper;

	@Resource
	private TaskRelateAssignPersonMapper taskRelateAssignPersonMapper;

	@Resource
	private UserInfoMapper userInfoMapper;

	@Resource
	private PaperMapper paperMapper;

	@Resource
	private DeptMapper deptMapper;

	@Resource
	private PaperRelateUserMapper paperRelateUserMapper;

	@Resource
	private SpreadUsedMapper spreadUsedMapper;

	@Resource
	private ParameterConfigureMapper parameterConfigureMapper;

	@Resource
	private PlayerRelateConsumeMapper playerRelateConsumeMapper;

	@Resource
	private PlayerMapper playerMapper;


	/**
	 * 删除记录
	 *
	 * @param id
	 * @return
	 * @throws Exception
	 */
	@Override
	public int deleteByPrimaryKey(String id) throws Exception {
		return this.taskMapper.deleteByPrimaryKey(id);
	}

	/**
	 * 批量删除记录
	 *
	 * @param ids
	 * @return
	 * @throws Exception
	 */
	@Override
	public int deleteByPrimaryKeys(List<String> ids) throws Exception {
		return this.taskMapper.deleteByPrimaryKeys(ids);
	}

	/**
	 * 批量删除记录
	 *
	 * @param ids
	 * @return
	 * @throws Exception
	 */
	@Override
	public int updateByKeys(List<String> ids) throws Exception {
		return this.taskMapper.updateByKeys(ids);
	}

	/**
	 * 插入记录
	 *
	 * @param record
	 * @return
	 * @throws Exception
	 */
	@Override
	public int insert(Task record) throws Exception {
		if (StringUtils.isBlank(record.getId())) {
			record.setId(PrimaryKeyGeneratorUtil.getInstance().getRandomKey());
		}
		record.setCreateTime(new Date());
		return this.taskMapper.insert(record);
	}

	/**
	 * 插入记录（仅非空值字段）
	 *
	 * @param record
	 * @return
	 * @throws Exception
	 */
	@Override
	public int insertSelective(Task record) throws Exception {
		if (StringUtils.isBlank(record.getId())) {
			record.setId(PrimaryKeyGeneratorUtil.getInstance().getRandomKey());
		}
		record.setCreateTime(new Date());
		return this.taskMapper.insertSelective(record);
	}

	/**
	 * 插入记录（仅非空值字段）
	 *
	 * @param recordVO
	 * @return
	 * @throws Exception
	 */
	@Override
	public int insertSelectiveByTaskVO(TaskVO recordVO) throws Exception {
		if (StringUtils.isBlank(recordVO.getId())) {
			recordVO.setId(PrimaryKeyGeneratorUtil.getInstance().getRandomKey());
		}
		recordVO.setCreateTime(new Date());
		return this.taskMapper.insertSelectiveByTaskVO(recordVO);
	}

	/**
	 * 批量插入
	 *
	 * @param list
	 * @return
	 * @throws Exception
	 */
	@Override
	public int insertBatch(List<TaskRelateAssignPerson> list) throws Exception {
		return this.taskRelateAssignPersonMapper.insertBatch(list);
	}

	/**
	 * 任务发布
	 *
	 * @param recordVO
	 * @return
	 * @throws Exception
	 */
	@Override
	public int insertSelectiveByTaskVOAndUserInfo(TaskVO recordVO, UserInfo userInfo) throws Exception {
		int result = 0;
		if (recordVO.getType() != null) {
			// 获取刚insert进去任务列表ID
			String taskId = PrimaryKeyGeneratorUtil.getInstance().getRandomKey();
			if (recordVO.getIsOnlineExam() == null) {
				recordVO.setIsOnlineExam(2);
			}
			recordVO.setId(taskId);
			recordVO.setIsDel(2);
			recordVO.setCreator(userInfo.getName());// 创建人
			recordVO.setCreatorId(userInfo.getId());
			recordVO.setCreateTime(new Date());

			// 维护任务-玩家信息
			List<TaskRelateMaintainUser> taskRelateMaintainUserList = recordVO.getTaskRelateMaintainUserList();
			if (recordVO.getType() == 1 && taskRelateMaintainUserList != null && taskRelateMaintainUserList.size() > 0) {
				for (TaskRelateMaintainUser relateMaintainUser : taskRelateMaintainUserList) {
					relateMaintainUser.setTaskId(taskId);
					if (relateMaintainUser.getNickName() != null && StringUtils.isNotEmpty(relateMaintainUser.getNickName())) {
						relateMaintainUser.setName(relateMaintainUser.getNickName());
					}
					String key = PrimaryKeyGeneratorUtil.getInstance().getRandomKey();
					relateMaintainUser.setId(key);
					relateMaintainUser.setCreateTime(new Date());
					relateMaintainUser.setUserType(2);// 标识的玩家
					this.taskRelateMaintainUserMapper.insertSelective(relateMaintainUser);
				}

			}

			// 推广任务 -主播信息
			if (recordVO.getType() == 2 && taskRelateMaintainUserList != null && taskRelateMaintainUserList.size() > 0) {
				recordVO.setState(1);//未完成
				recordVO.setIsEnable(1);// 默认上架
				for (TaskRelateMaintainUser relateMaintainUser : taskRelateMaintainUserList) {
					relateMaintainUser.setTaskId(taskId);
					UserInfo userInfo1 = this.userInfoMapper.selectByPrimaryKey(relateMaintainUser.getUserId());
					String key = PrimaryKeyGeneratorUtil.getInstance().getRandomKey();
					relateMaintainUser.setId(key);
					relateMaintainUser.setUserType(1);// 标识的主播
					relateMaintainUser.setCreateTime(new Date());
					relateMaintainUser.setIsOnline(1);//
					relateMaintainUser.setAnchorId(relateMaintainUser.getOtherAccount());
					this.taskRelateMaintainUserMapper.insertSelective(relateMaintainUser);
					SpreadLimit spreadLimit = this.spreadLimitMapper.selectByObjId(relateMaintainUser.getUserId());
					if (spreadLimit != null && spreadLimit.getState() == 1) {
						// 扣减上限链接数据
						this.spreadLimitMapper.SubtractByObjId(relateMaintainUser.getUserId(), recordVO.getLinkNum());
					}
				}

			}

			// 学习任务
			List<TaskRelateCourse> taskTaskRelateCourseList = recordVO.getTaskRelateCourseList();
			// List<TaskRelateCourseUser> taskRelateCourseUserList = recordVO.getTaskRelateCourseUserList();
			if (recordVO.getType() == 3 && taskTaskRelateCourseList != null && taskTaskRelateCourseList.size() > 0) {
				int prority = 1;
				for (TaskRelateCourse taskRelateCourse : taskTaskRelateCourseList) {
					// UserInfo userInfo1 = this.userInfoMapper.selectByPrimaryKey(taskRelateCourseUser.getUserId());
					String key = PrimaryKeyGeneratorUtil.getInstance().getRandomKey();
					taskRelateCourse.setId(key);
					taskRelateCourse.setTaskId(taskId);
					taskRelateCourse.setPrority(prority);
					taskRelateCourse.setCreateTime(new Date());
					prority = prority + 1;
					this.taskRelateCourseMapper.insertSelective(taskRelateCourse);
				}
			}
			// 培训任务
			/**
			 * 注：培训任务指定类型存在account字段 主播-1 业务员-2，批量插入体系中
			 */
			List<TaskRelateCourse> taskRelateCourseList = recordVO.getTaskRelateCourseList();
			if (recordVO.getType() == 4 && taskRelateCourseList != null && taskRelateCourseList.size() > 0) {
				int prority = 1;
				for (TaskRelateCourse taskRelateCourse : taskRelateCourseList) {
					String key = PrimaryKeyGeneratorUtil.getInstance().getRandomKey();
					taskRelateCourse.setPrority(prority);
					taskRelateCourse.setTaskId(taskId);
					taskRelateCourse.setId(key);
					taskRelateCourse.setCreateTime(new Date());
					taskRelateCourse.setPrority(prority);
					prority = prority + 1;
					this.taskRelateCourseMapper.insertSelective(taskRelateCourse);
					prority = prority + 1;
				}
			}

			// 指派完成人
			List<TaskRelateAssignPerson> taskRelateAssignPersonList = recordVO.getTaskRelateAssignPersonList();
			if (taskRelateAssignPersonList != null && taskRelateAssignPersonList.size() > 0) {
				for (TaskRelateAssignPerson taskRelateAssignPerson : taskRelateAssignPersonList) {
					String key = PrimaryKeyGeneratorUtil.getInstance().getRandomKey();
					taskRelateAssignPerson.setTaskId(taskId);
					taskRelateAssignPerson.setType(1);// 指派
					taskRelateAssignPerson.setState(0);
					taskRelateAssignPerson.setId(key);
					taskRelateAssignPerson.setCreateTime(new Date());
					// 主播
					if (recordVO.getUserType() == 1) {
						taskRelateAssignPerson.setUserType(1);
					}
					// 业务员
					if (recordVO.getUserType() == 2) {
						taskRelateAssignPerson.setUserType(2);
					}
					this.taskRelateAssignPersonMapper.insertSelective(taskRelateAssignPerson);
				}

			}
			// 培训任务指派人处理
			if (taskRelateAssignPersonList == null && recordVO.getType() == 4 && recordVO.getAccount() != null) {
				List<TaskRelateAssignPerson> relateAssignPersonList = new ArrayList<>();
				TaskRelateAssignPerson taskRelateAssignPerson = new TaskRelateAssignPerson();
				String key = PrimaryKeyGeneratorUtil.getInstance().getRandomKey();
				taskRelateAssignPerson.setTaskId(taskId);
				taskRelateAssignPerson.setType(1);// 指派
				taskRelateAssignPerson.setState(0);
				taskRelateAssignPerson.setIsDel(0);
				taskRelateAssignPerson.setIsRead(0);
				taskRelateAssignPerson.setId(key);
				taskRelateAssignPerson.setCreateTime(new Date());
				if (recordVO.getAccount() == 1) {
					taskRelateAssignPerson.setAccount("1");
					taskRelateAssignPerson.setUserId("1");
					taskRelateAssignPerson.setUserType(1);
					taskRelateAssignPerson.setName("主播");
				} else {
					taskRelateAssignPerson.setAccount("2");
					taskRelateAssignPerson.setUserId("2");
					taskRelateAssignPerson.setUserType(2);
					taskRelateAssignPerson.setName("业务员");
				}
				this.taskRelateAssignPersonMapper.insertSelective(taskRelateAssignPerson);

				List<UserInfo> userInfoList = new ArrayList<>();
				// 查询体系下的用户
				if (userInfo.getSourceSys() == 0) {
					// 查询所有的业务或主播
					UserInfo userInfo1 = new UserInfo();
					if (recordVO.getAccount() == 1) { // 主播
						userInfo1.setType(11);
					} else {
						userInfo1.setType(6);
					}
					userInfo1.setStatus(1);// 启用
					userInfo1.setIsDel(0);// 未删除
					userInfoList = this.userInfoMapper.selectList(userInfo1);

				} else {
					Dept dept = this.deptMapper.selectByPrimaryKey(userInfo.getDeptId());
					if (dept != null) {
						List<String> deptIdList = new ArrayList<>();
						if ((userInfo.getSourceSys() == 2 && userInfo.getType() == 5) || (userInfo.getSourceSys() == 1 && userInfo.getType() == 3)) { // 小组
							deptIdList.add(userInfo.getDeptId());
						} else {
							this.selectDeptSon(dept.getCode(), deptIdList);
						}

						// Acconut =1 主播 Account =2 业务员
						if (recordVO.getAccount() == 1) { // 主播
							userInfoList = this.userInfoMapper.selectAnchorInfoByDeptIds(deptIdList);
						} else {
							userInfoList = this.userInfoMapper.selectSalesUserInfoByDeptIds(deptIdList);
						}
					}
				}

				if (userInfoList != null && userInfoList.size() > 0) {
					for (UserInfo info : userInfoList) {
						TaskRelateAssignPerson relateAssignPerson = new TaskRelateAssignPerson();
						if (recordVO.getAccount() == 1) { // 主播
							relateAssignPerson.setUserType(1);
						} else {
							relateAssignPerson.setUserType(2);
						}
						String key2 = PrimaryKeyGeneratorUtil.getInstance().getRandomKey();
						relateAssignPerson.setUserId(info.getId());
						relateAssignPerson.setId(key2);
						relateAssignPerson.setName(info.getName());
						relateAssignPerson.setAccount(info.getAccount());
						relateAssignPerson.setTaskId(taskId);
						relateAssignPerson.setType(1);// 指派
						relateAssignPerson.setState(0);
						relateAssignPerson.setIsDel(0);
						relateAssignPerson.setIsRead(0);
						relateAssignPersonList.add(relateAssignPerson);
					}
				}

				// 批量插入
				if (relateAssignPersonList != null && relateAssignPersonList.size() > 0) {
					this.taskRelateAssignPersonMapper.insertBatch(relateAssignPersonList);
				}

			}
			result = this.taskMapper.insertSelectiveByTaskVO(recordVO);
		}
		return result;
	}

	/**
	 * 更新记录
	 *
	 * @param record
	 * @return
	 * @throws Exception
	 */
	@Override
	public int updateByPrimaryKey(Task record) throws Exception {
		record.setUpdateTime(new Date());
		if (record.getFinishTime() != null) {
			record.setFinishTime(new Date());
		}
		return this.taskMapper.updateByPrimaryKey(record);
	}

	/**
	 * 更新记录
	 *
	 * @param recordVO
	 * @return
	 * @throws Exception
	 */
	@Override
	public int updateByTaskVO(TaskVO recordVO) throws Exception {
		recordVO.setUpdateTime(new Date());
		if (recordVO.getFinishTime() != null) {
			recordVO.setFinishTime(new Date());
		}
		return this.taskMapper.updateByTaskVO(recordVO);
	}

	/**
	 * 定时更新状态（定时任务）
	 *
	 * @param id
	 * @return
	 * @throws Exception
	 */
	@Override
	public int updateTaskStateByKey(String id) throws Exception {
		return this.taskMapper.updateTaskStateByKey(id);
	}

	/**
	 * 更新记录（仅非空值字段）
	 *
	 * @param record
	 * @return
	 * @throws Exception
	 */
	@Override
	public int updateByPrimaryKeySelective(Task record) throws Exception {
		record.setUpdateTime(new Date());
		return this.taskMapper.updateByPrimaryKeySelective(record);
	}

	@Override
	public int updateByPrimaryKeySelectiveTenantCode(Task record, String tenantCode) throws Exception {
		if (StringUtils.isNotEmpty(tenantCode)) {
			TenantCodeUtil.getInstance().createServerTenantCode(tenantCode);
		}
		return this.updateByPrimaryKeySelective(record);
	}

	/**
	 * 上下架
	 * @param task
	 * @return
	 * @throws Exception
	 */
	@Override
	public int updateByTaskId(Task task) throws Exception {
		if(task.getIsEnable() == 0) { //下架
			this.taskRelateAssignPersonMapper.deleteByTaskId(task.getId());
			//恢复上限加一
			List<TaskRelateAssignPerson> relateAssignPersonList = this.taskRelateAssignPersonMapper.selectListByTaskId(task.getId());
			if (relateAssignPersonList != null && relateAssignPersonList.size() > 0) {
				for (TaskRelateAssignPerson relateAssignPerson : relateAssignPersonList) {
					if(relateAssignPerson.getUserId() != null && StringUtils.isNotBlank(relateAssignPerson.getUserId())){
						SpreadUsed spreadUsed = this.spreadUsedMapper.selectSpreadUsedByUserId(relateAssignPerson.getUserId());
						if(spreadUsed != null){
							spreadUsed.setUsedNum(spreadUsed.getUsedNum() + 1);
							this.spreadUsedMapper.updateByPrimaryKeySelective(spreadUsed);
						}
					}
				}
			}
		}
		task.setIsReach(0);
		return this.updateByPrimaryKeySelective(task);
	}

	/**
	 * 编辑任务
	 *
	 * @param recordVO
	 * @return
	 * @throws Exception
	 */
	@Override
	public int updateByTaskVOSelective(TaskVO recordVO, UserInfo userInfo) throws Exception {
		String taskId = recordVO.getId();
		if (recordVO.getType() == 1 || recordVO.getType() == 2) {
			// 先把原来的业务员上限-1
			// this.spreadLimitMapper.updateSubtractById(taskId);//-1
			TaskRelateMaintainUser taskRelateMaintainUser = new TaskRelateMaintainUser();
			taskRelateMaintainUser.setTaskId(taskId);
			List<TaskRelateMaintainUser> relateMaintainUserList = this.taskRelateMaintainUserMapper.selectList(taskRelateMaintainUser);
			if (relateMaintainUserList != null && relateMaintainUserList.size() > 0) {
				for (TaskRelateMaintainUser relateMaintainUser : relateMaintainUserList) {
					this.taskRelateMaintainUserMapper.deleteByPrimaryKey(relateMaintainUser.getId());
				}
			}

			List<TaskRelateMaintainUser> taskRelateMaintainUserList = recordVO.getTaskRelateMaintainUserList();
			if (taskRelateMaintainUserList != null && taskRelateMaintainUserList.size() > 0) {
				for (TaskRelateMaintainUser relateMaintainUser : taskRelateMaintainUserList) {
					relateMaintainUser.setUpdateTime(new Date());
					this.taskRelateMaintainUserMapper.insertSelective(relateMaintainUser);
					this.spreadLimitMapper.updateCountById(taskId);// +1
				}
			}
		}
		if (recordVO.getType() == 3) {
			List<TaskRelateCourse> relateCourseList = recordVO.getTaskRelateCourseList();
			if (relateCourseList != null && relateCourseList.size() > 0) {
				TaskRelateCourse taskRelateCourse = new TaskRelateCourse();
				taskRelateCourse.setTaskId(taskId);
				List<TaskRelateCourse> taskRelateCourseList = this.taskRelateCourseMapper.selectList(taskRelateCourse);
				if (taskRelateCourseList != null && taskRelateCourseList.size() > 0) {
					for (TaskRelateCourse relateCourse : taskRelateCourseList) {
						this.taskRelateCourseMapper.deleteByPrimaryKey(relateCourse.getId());
					}
				}
				int prority = 1;
				for (TaskRelateCourse taskRelateCourses : relateCourseList) {
					String key = PrimaryKeyGeneratorUtil.getInstance().getRandomKey();
					taskRelateCourses.setTaskId(taskId);
					taskRelateCourses.setId(key);
					taskRelateCourses.setTaskId(taskId);
					taskRelateCourse.setCreateTime(new Date());
					taskRelateCourse.setPrority(prority);
					prority = prority + 1;
					this.taskRelateCourseMapper.insertSelective(taskRelateCourses);
				}
			}
		}
		if (recordVO.getType() == 4) {
			List<TaskRelateCourse> taskRelateCourseList = recordVO.getTaskRelateCourseList();
			if (taskRelateCourseList != null && taskRelateCourseList.size() > 0) {
				TaskRelateCourse taskRelateCourse = new TaskRelateCourse();
				taskRelateCourse.setTaskId(taskId);
				List<TaskRelateCourse> taskRelateCourseLists = this.taskRelateCourseMapper.selectList(taskRelateCourse);
				if (taskRelateCourseLists != null && taskRelateCourseLists.size() > 0) {
					for (TaskRelateCourse courseList : taskRelateCourseLists) {
						this.taskRelateCourseMapper.deleteByPrimaryKey(courseList.getId());
					}
				}
				int prority = 1;
				for (TaskRelateCourse taskRelateCoursese : taskRelateCourseList) {
					String key = PrimaryKeyGeneratorUtil.getInstance().getRandomKey();
					taskRelateCoursese.setTaskId(taskId);
					taskRelateCoursese.setId(key);
					taskRelateCourse.setCreateTime(new Date());
					taskRelateCourse.setPrority(prority);
					prority = prority + 1;
					this.taskRelateCourseMapper.insertSelective(taskRelateCoursese);
				}
			}
		}
		// 指派人
		List<TaskRelateAssignPerson> taskRelateAssignPersonList = recordVO.getTaskRelateAssignPersonList();
		if (taskRelateAssignPersonList != null && taskRelateAssignPersonList.size() > 0 && recordVO.getType() != 4) {
			// 先删除库中数据
			List<TaskRelateAssignPerson> personList = this.taskRelateAssignPersonMapper.selectListByTaskId(taskId);
			for (TaskRelateAssignPerson taskRelateAssignPerson : personList) {
				this.taskRelateAssignPersonMapper.deleteByPrimaryKey(taskRelateAssignPerson.getId());
			}
			for (TaskRelateAssignPerson taskRelateAssignPerson : taskRelateAssignPersonList) {
				String key = PrimaryKeyGeneratorUtil.getInstance().getRandomKey();
				// this.spreadLimitMapper.updateSubtractById(taskRelateAssignPerson.getUserId());//-1
				taskRelateAssignPerson.setTaskId(taskId);
				taskRelateAssignPerson.setId(key);
				taskRelateAssignPerson.setState(0);
				taskRelateAssignPerson.setType(1);
				taskRelateAssignPerson.setCreateTime(new Date());
				this.taskRelateAssignPersonMapper.insertSelective(taskRelateAssignPerson);
				// this.spreadLimitMapper.updateCountById(taskRelateAssignPerson.getUserId());//+1
			}
		}
		recordVO.setUpdateTime(new Date());
		return this.taskMapper.updateByTaskVOSelective(recordVO);
	}

	/**
	 * 查询记录
	 *
	 * @param id
	 * @return
	 * @throws Exception
	 */
	@Override
	public Task selectByPrimaryKey(String id) throws Exception {
		return this.taskMapper.selectByPrimaryKey(id);
	}

	/**
	 * 查询记录（租户模式）
	 *
	 * @param id
	 * @return
	 * @throws Exception
	 */
	@Override
	public Task selectByPrimaryKeyTenantCode(String id, String tenantCode) throws Exception {
		if (StringUtils.isNotEmpty(tenantCode)) {
			TenantCodeUtil.getInstance().createServerTenantCode(tenantCode);
		}
		return this.selectByPrimaryKey(id);
	}

	/**
	 * 查询记录
	 *
	 * @param id
	 * @return
	 * @throws Exception
	 */
	@Override
	public TaskVO selectByTaskVOPrimaryKey(String id, String userId) throws Exception {
		TaskVO task = this.taskMapper.selectByTaskVOPrimaryKey(id);
		// 查询考卷名称
		if (task.getIsOnlineExam() != null && task.getIsOnlineExam() == 1) {
			Paper paper = this.paperMapper.selectByPrimaryKey(task.getPaperId());
			if (paper != null && paper.getName() != null) {
				task.setPaperName(paper.getName());
			}
		}
		// 关联完成人
		TaskRelateAssignPerson relateAssignPerson = new TaskRelateAssignPerson();
		relateAssignPerson.setUserId(userId);
		relateAssignPerson.setTaskId(id);
		List<TaskRelateAssignPerson> taskRelateAssignPersonList = this.taskRelateAssignPersonMapper.selectList(relateAssignPerson);
		if (taskRelateAssignPersonList != null && taskRelateAssignPersonList.size() > 0) {
			task.setTaskRelateAssignPersonList(taskRelateAssignPersonList);
			if (task.getType() == 4) {
				for (TaskRelateAssignPerson taskRelateAssignPerson : taskRelateAssignPersonList) {
					Integer userType = taskRelateAssignPerson.getUserType();
					task.setAccount(userType);
				}
			}
		}
		// 关联维护用户
		TaskRelateMaintainUser maintainUser = new TaskRelateMaintainUser();
		maintainUser.setTaskId(id);
		List<TaskRelateMaintainUser> taskRelateMaintainUserList = this.taskRelateMaintainUserMapper.selectList(maintainUser);
		if (taskRelateMaintainUserList != null && taskRelateMaintainUserList.size() > 0) {
			task.setTaskRelateMaintainUserList(taskRelateMaintainUserList);
		}
		// 关联课程
		TaskRelateCourse taskRelateCourse = new TaskRelateCourse();
		taskRelateCourse.setTaskId(id);
		List<TaskRelateCourse> taskRelateCourseList = this.taskRelateCourseMapper.selectList(taskRelateCourse);
		if (taskRelateCourseList != null && taskRelateCourseList.size() > 0) {
			task.setTaskRelateCourseList(taskRelateCourseList);
		}
		// 任务课程关联用户
		TaskRelateCourseUser taskRelateCourseUser = new TaskRelateCourseUser();
		taskRelateCourseUser.setTaskId(id);
		List<TaskRelateCourseUser> taskRelateCourseUserList = this.taskRelateCourseUserMapper.selectList(taskRelateCourseUser);
		if (taskRelateCourseUserList != null && taskRelateCourseUserList.size() > 0) {
			task.setTaskRelateCourseUserList(taskRelateCourseUserList);
		}
		return task;
	}

	/**
	 * 查询列表
	 *
	 * @param record
	 * @return
	 * @throws Exception
	 */
	@Override
	public List<Task> selectList(Task record) throws Exception {
		return this.taskMapper.selectList(record);
	}

	/**
	 * 查询列表_租户模式（定时任务）
	 *
	 * @param record
	 * @return
	 * @throws Exception
	 */
	@Override
	public List<Task> selectList(Task record, String tenantCode) throws Exception {
		if (StringUtils.isNotEmpty(tenantCode)) {
			TenantCodeUtil.getInstance().createServerTenantCode(tenantCode);
		}
		return selectList(record);
	}

	/**
	 * 接单中心_分页查询列表
	 *
	 * @param params
	 * @param page
	 * @return
	 * @throws Exception
	 */
	@Override
	public BasePage<Task> selectListByPage(Map<String, Object> params, BasePage<Task> page, UserInfo userInfo) throws Exception {
		SimpleDateFormat format = new SimpleDateFormat("yyyy年M月dd日");
		params.put("page", page);
		params.put("userId", userInfo.getId());
		List<Task> list = this.taskMapper.selectListByPage(params);
		list.removeAll(Collections.singleton(null));
		if (list != null && list.size() > 0) {
			List<String> anchorIdList = new ArrayList<>();
			for (int i = 0, len = list.size(); i < len; i++) {
				Task task = list.get(i);
				// 判读接收这个任务的上限是否超出设置的数量
				if (task != null) {
					// 该任务设定的链接数和以被抢的量
					/*
					 * List<TaskRelateAssignPerson> personList = this.taskRelateAssignPersonMapper.selectListByTaskId(task.getId()); int size = personList.size(); int linkNum = 0; if (task.getLinkNum() != null) { linkNum = task.getLinkNum(); }
					 */
					// 判断我是否已经抢单了
					Map<String, Object> map = new HashMap<>();
					map.put("userId", userInfo.getId());
					map.put("taskId", task.getId());
					map.put("type", 2);
					if (task.getOtherAccount() != null && StringUtils.isNotBlank(task.getOtherAccount())) {
						anchorIdList.add(task.getOtherAccount());
					}
					/*
					 * TaskRelateAssignPerson taskRelateAssignPerson = this.taskRelateAssignPersonMapper.selectIsMyTask(map);
					 *
					 * //请求接口，判断主播是否在线 /* int isLive = 0; TreeMap<String, Object> paramMap = new TreeMap<>(); if (task.getOtherAccount() != null) { paramMap.put("anchorIds", task.getOtherAccount()); anchorIdList.add(task.getOtherAccount()); Map resultMap = QueryAppUtil.query("anchorOnlineUrl", 1, paramMap); Integer code = Integer.parseInt(resultMap.get("code").toString()); if (code == 1) { //成功 isLive =
					 * Integer.parseInt(resultMap.get("data").toString()); } else { logger.error(resultMap.get("msg").toString()); //throw new Exception("接口请求失败！" + (String) resultMap.get("msg")); } }
					 *
					 * //判断任务数量是否超额、是否已接过、主播是否在线，满足之一不显示 if (size >= linkNum || taskRelateAssignPerson != null || isLive == 1) { list.remove(i); len--; i--; continue; }
					 */
					/* int isLive = 0;
					 TreeMap<String, Object> paramMap = new TreeMap<>();
					 if (task.getOtherAccount() != null) {
					 	paramMap.put("anchorIds", task.getOtherAccount());
					 }
					 anchorIdList.add(task.getOtherAccount());
					 Map resultMap = QueryAppUtil.query("anchorOnlineUrl", 1, paramMap);
					 Integer code = Integer.parseInt(resultMap.get("code").toString());
					 if (code == 1) { //成功 isLive =
						 isLive = Integer.parseInt(resultMap.get("data").toString());
					 } else {
					 	logger.error(resultMap.get("msg").toString());
					 }*/

					if (task.getCreateTime() != null) {
						Date createTime = task.getCreateTime();
						// 距离发布时间计算
						task.setTimeforMat(TimeFormatUtil.timeUtile(createTime));
					}
					if (task.getEndTime() != null) {
						// 时间日期格式的转换
						String format1 = format.format(task.getEndTime());
						Date parseendTime = format.parse(format1);// 类型转换格式
						task.setEndTime(parseendTime);
					}
					// list.set(i, task);
				}
			}
			if (anchorIdList != null && anchorIdList.size() > 0) {
				List<Anchor> anchorList = new ArrayList<>();
				TreeMap<String, Object> paramMap = new TreeMap<>();
				paramMap.put("anchorIds", StringUtils.join(anchorIdList, ","));
				try {
					Map resultMap = QueryAppUtil.query("anchorInfoBatchUrl", 1, paramMap);
					if (resultMap != null) {
						Integer code = Integer.parseInt(resultMap.get("code").toString());
						String msg = (String) resultMap.get("msg");
						if (code == 1) {
							String data = (String) resultMap.get("data");
							anchorList = JsonUtils.parseArray(data, Anchor.class);
						} else {
							logger.error(msg);
						}
					}
				} catch (Exception ex) {
					logger.error(ex.getMessage());
				}
				if (anchorList != null && anchorList.size() > 0) {
					for (int i = 0; i < list.size(); i++) {
						Task task = list.get(i);
						String otherAccount = task.getOtherAccount();
						if (otherAccount == null || StringUtils.isBlank(otherAccount)) {
							continue;
						} else {
							task.setAnchorImgUrl(getAnchorHeadPortrait(anchorList, otherAccount));
						}
					}
				}
			}
		}
		page.setResults(list);
		return page;
	}

	private String getAnchorHeadPortrait(List<Anchor> anchorList, String anchorId) throws Exception {
		String headPortraitImg = "";
		if (anchorList != null && anchorList.size() > 0) {
			for (int i = 0; i < anchorList.size(); i++) {
				if (anchorList.get(i).getAnchorId().equals(anchorId)) {
					headPortraitImg = anchorList.get(i).getAnchorHeadPortrait();
					break;
				}
			}
		}
		return headPortraitImg;
	}

	/**
	 * 我的任务列表_分页查询
	 *
	 * @param params
	 * @param page
	 * @return
	 * @throws Exception
	 */
	@Override
	public BasePage<Task> selectCenterListByPage(Map<String, Object> params, BasePage<Task> page, UserInfo userInfo) throws Exception {
		params.put("page", page);
		List<Task> list = this.myTaskList(params, page, userInfo);
		if (list != null && list.size() > 0) {
			for (Task task : list) {
				updateTask(task, userInfo);
			}
		}
		page.setResults(list);
		return page;
	}

	/**
	 * 运管任务分页查询
	 *
	 * @param params
	 * @param page
	 * @return
	 * @throws Exception
	 */
	@Override
	public BasePage<Task> selectAdminListByPage(Map<String, Object> params, BasePage<Task> page, UserInfo userInfo) throws Exception {
		params.put("page", page);
		List<Task> list = this.AdminTaskList(params, page, userInfo);
		page.setResults(list);
		return page;
	}

	/**
	 * 我的任务列表
	 * @param params
	 * @param page
	 * @param userInfo
	 * @return
	 * @throws Exception
	 */
	private List<Task> myTaskList(Map<String, Object> params, BasePage<Task> page, UserInfo userInfo) throws Exception{
		// 分级查询
		if ((userInfo.getSourceSys() == 2 && userInfo.getType() == 6) || (userInfo.getSourceSys() == 1 && userInfo.getType() == 11)) { // 主播或业务员
			params.put("userId", userInfo.getId());
			params.put("creatorId", userInfo.getId());
		} else {
			Dept dept = this.deptMapper.selectByPrimaryKey(userInfo.getDeptId());
			params.put("creatorId", userInfo.getId());
			List<String> deptIdList = new ArrayList<>();
			// 小组
			/*if ((dept.getSourceSys() == 2 && dept.getType() == 5) || (dept.getSourceSys() == 1 && dept.getType() == 3)) {
				deptIdList.add(userInfo.getDeptId());
			} else {
				this.selectDeptSon(dept.getCode(), deptIdList);
			}*/
			deptIdList.add(userInfo.getDeptId());
			this.selectDeptSon(dept.getCode(), deptIdList);
			List<String> userIdList = new ArrayList<>();
			if (userInfo.getSourceSys() == 1) { // 内容类
				userIdList = this.userInfoMapper.selectAnchorIdsByDeptIds(deptIdList);
			} else {
				userIdList = this.userInfoMapper.selectSalesmanUserIdsByDeptIds(deptIdList);
			}

			if(!userIdList.contains(userInfo.getId())) {
				userIdList.add(userInfo.getId());//包括自己
			}
			if (userIdList != null && userIdList.size() > 0) {
				params.put("userIdList", userIdList);
			}
		}
		List<Task> list = this.taskMapper.selectCenterListByPage(params);
		// 处理培训任务
		if ((userInfo.getSourceSys() == 2 && userInfo.getType() != 6) || (userInfo.getSourceSys() == 1 && userInfo.getType() != 11)) { // 不是业务员或者主播
			if (list != null && list.size() > 0) {
				for (Task task : list) {
					if (task.getType() == 2) {
						// 维护对象
						TaskRelateMaintainUser relateMaintainUser = this.taskRelateMaintainUserMapper.selectByTaskId(task.getId());
						if (relateMaintainUser != null && relateMaintainUser.getName() != null) {
							task.setMaintainUser(relateMaintainUser.getName());
						}
						/*//处理下架人员
						if (task.getAssignPersionId() != null && StringUtils.isNotBlank(task.getAssignPersionId())) {
							//判断指派人是否有被删的数据
							TaskRelateAssignPerson taskRelateAssignPerson = this.taskRelateAssignPersonMapper.selectPaperIsMyTask(task.getId(), task.getAssignPersionId());
							if (taskRelateAssignPerson == null) {
								task.setAssignPersionId("");
								task.setAssignPersionName("");
							}
						}*/
						// 接单人员
						List<TaskRelateAssignPerson> taskRelateAssignPersonList = this.taskRelateAssignPersonMapper.selectListByTaskId(task.getId());
						if (taskRelateAssignPersonList != null && taskRelateAssignPersonList.size() > 0) {
							StringBuffer assignPerson = new StringBuffer();
							for (TaskRelateAssignPerson taskRelateAssignPerson : taskRelateAssignPersonList) {
								if (taskRelateAssignPerson.getName() != null) {
									assignPerson.append(taskRelateAssignPerson.getName() + ",");
								}
							}
							task.setAssignPersionName(assignPerson.substring(0, assignPerson.length() - 1));
						}
					}

					if (task.getType() == 4) { // 培训任务
						List<TaskRelateAssignPerson> relateAssignPersonList = this.taskRelateAssignPersonMapper.selectListByTaskId(task.getId());
						if (relateAssignPersonList != null && relateAssignPersonList.size() > 0) {
							for (TaskRelateAssignPerson taskRelateAssignPerson : relateAssignPersonList) {
								if (taskRelateAssignPerson.getAccount().equals("1")) {
									task.setAssignPersionName("主播");
									task.setId(taskRelateAssignPerson.getTaskId());
									break;
								}
								if (taskRelateAssignPerson.getAccount().equals("2")) {
									task.setAssignPersionName("业务员");
									task.setId(taskRelateAssignPerson.getTaskId());
									break;
								}

							}
						}
					}

				}
			}
		}
		return list;
	}

	/**
	 * 开放平台任务列表
	 * @param params
	 * @param page
	 * @param userInfo
	 * @return
	 * @throws Exception
	 */
	private List<Task> AdminTaskList(Map<String, Object> params, BasePage<Task> page, UserInfo userInfo) throws Exception{
		List<Task> list = this.taskMapper.selectAdminListByPage(params);
		// 推广任务对维护人员和接单人员做处理
		for (Task task : list) {
			if (task != null && task.getType() != null) {
				if (task.getType() == 2) {
					// 维护对象
					TaskRelateMaintainUser relateMaintainUser = this.taskRelateMaintainUserMapper.selectByTaskId(task.getId());
					if (relateMaintainUser != null && relateMaintainUser.getName() != null) {
						task.setMaintainUser(relateMaintainUser.getName());

						// 查询用户数，优质用户数
						UserInfo userInfo1 = this.userInfoMapper.selectByPrimaryKey(relateMaintainUser.getUserId());
						if(userInfo1!=null && StringUtils.isNotBlank(userInfo1.getOtherAccount())){
							// 查询用户数
							Map<String,Object> query = new HashMap<>();
							query.put("anchorId",userInfo1.getOtherAccount());
							query.put("createTime",task.getCreateTime());
							Integer extensionUserNum = this.playerMapper.selectPlayerNumByAnchorId(query);

							//查询优质用户数
							Integer extensionHighQualityNum =0; //this.playerMapper.selectHighQualityUserNumByAnchorId(query);
							task.setExtensionUserNum(extensionUserNum);
							task.setExtensionHighQualityNum(extensionHighQualityNum);
						}
					}
					//处理下架人员
					if(task.getAssignPersionId() != null && StringUtils.isNotBlank(task.getAssignPersionId())){
						//判断指派人是否有被删的数据
						TaskRelateAssignPerson taskRelateAssignPerson = this.taskRelateAssignPersonMapper.selectPaperIsMyTask(task.getId(), task.getAssignPersionId());
						if(taskRelateAssignPerson == null){
							task.setAssignPersionId("");
							task.setAssignPersionName("");
						}
					}
					// 接单人员
					List<TaskRelateAssignPerson> taskRelateAssignPersonList = this.taskRelateAssignPersonMapper.selectListByTaskId(task.getId());
					if (taskRelateAssignPersonList != null && taskRelateAssignPersonList.size() > 0) {
						StringBuffer assignPerson = new StringBuffer();
						for (TaskRelateAssignPerson taskRelateAssignPerson : taskRelateAssignPersonList) {
							if (taskRelateAssignPerson.getName() != null) {
								assignPerson.append(taskRelateAssignPerson.getName() + ",");
							}
						}
						task.setAssignPersionName(assignPerson.substring(0, assignPerson.length() - 1));
					}
				}

				// 处理培训任务
				if (task.getType() == 4) { // 培训任务
					List<TaskRelateAssignPerson> relateAssignPersonList = this.taskRelateAssignPersonMapper.selectListByTaskId(task.getId());
					if (relateAssignPersonList != null && relateAssignPersonList.size() > 0) {
						for (TaskRelateAssignPerson taskRelateAssignPerson : relateAssignPersonList) {
							if (taskRelateAssignPerson.getAccount().equals("1")) {
								task.setAssignPersionName("主播");
								task.setId(taskRelateAssignPerson.getTaskId());
								break;
							}
							if (taskRelateAssignPerson.getAccount().equals("2")) {
								task.setAssignPersionName("业务员");
								task.setId(taskRelateAssignPerson.getTaskId());
								break;
							}

						}
					}
				}
			}
			updateTask(task, userInfo);
		}
		return list;
	}

	/**
	 * 更新考试是否出现查看考卷按钮及考试按钮
	 *
	 * @param task
	 * @param userInfo
	 * @throws Exception
	 */
	private void updateTask(Task task, UserInfo userInfo) throws Exception {
		task.setIsPass(2);
		// 培训/学习任务的是否参加考试 0否 1是
		if (task.getIsOnlineExam() != null) {
			if (task.getIsOnlineExam() == 1 && (task.getType() == 4 || task.getType() == 3)) {

				if (task.getCreatorId().equals(userInfo.getId()) || task.getAssignPersionId().equals(userInfo.getId()))// 任务发布者或是任务作答者 才能查看考卷
				{
					task.setIsViewPaper(1);
				} else {
					task.setIsViewPaper(0);
				}
				PaperRelateUser paperRelateUser = getPaperRelateUserByUserId(task.getAssignPersionId(), task.getPaperId(), task.getId());
				// 考试不及格
				if (paperRelateUser != null) {
					if (paperRelateUser.getState() == 2)// 提交
					{
						if (paperRelateUser.getIsGrade() == 0) // 尚未评卷
						{
							task.setIsExam(1);
						} else// 如果有评卷，需要判断是否通过，通过则不出现，否则则出现
						{
							BigDecimal score = paperRelateUser.getScore();
							String pageId = paperRelateUser.getPaperId();
							if (pageId != null && StringUtils.isNotBlank(pageId)) {
								Paper paper = paperMapper.selectByPrimaryKey(pageId);
								BigDecimal passingScore = paper == null ? new BigDecimal(BigInteger.ZERO) : paper.getPassingScore();

								if (score.compareTo(passingScore) > -1) {
									task.setIsExam(1);
									task.setIsPass(1);
								} else {
									task.setIsExam(0);
									task.setIsPass(0);
								}
							} else {
								task.setIsExam(0);
							}
						}
					} else {
						task.setIsExam(0);
					}
				} else {
					task.setIsExam(0);// 未参加考试
				}
			}
		}
	}

	private PaperRelateUser getPaperRelateUserByUserId(String userId, String pagerId, String taskId) throws Exception {
		// 判断是否参加考试
		PaperRelateUser tempPaperRelateUser = new PaperRelateUser();
		tempPaperRelateUser.setCreatorId(userId);
		tempPaperRelateUser.setPaperId(pagerId);
		tempPaperRelateUser.setTaskId(taskId);
		List<PaperRelateUser> paperRelateUserList = this.paperRelateUserMapper.selectList(tempPaperRelateUser);
		PaperRelateUser paperRelateUser = null;
		if (paperRelateUserList != null && paperRelateUserList.size() > 0) {
			if (paperRelateUserList.size() == 1) {
				paperRelateUser = paperRelateUserList.get(0);
			} else {
				BigDecimal score = new BigDecimal(BigInteger.ZERO);
				for (int i = 0; i < paperRelateUserList.size(); i++) {
					PaperRelateUser paperRelateUser1 = paperRelateUserList.get(i);
					BigDecimal tempScore = paperRelateUser1.getScore() == null ? new BigDecimal(BigInteger.ZERO) : paperRelateUser1.getScore();
					if (tempScore.compareTo(score) > -1) {
						paperRelateUser = paperRelateUser1;
						score = tempScore;
					}
				}
			}
		}
		return paperRelateUser;
	}

	/**
	 * 任务列表_导出
	 *
	 * @param params
	 * @return
	 * @throws Exception
	 */
	@Override
	public List<Task> selectTaskExport(Map<String, Object> params, UserInfo userInfo) throws Exception {
		List<Task> list = new ArrayList<>();
		BasePage<Task> page = new BasePage();
		page.setPageNo(1);
		page.setPageSize(999999);
		params.put("page", page);
		if(userInfo.getSourceSys() ==0){
			list = this.AdminTaskList(params,page,userInfo);
		}else {
			list = this.myTaskList(params,page,userInfo);
		}
		return list;
	}

	@Override
	public Task selectByTaskid(String id) throws Exception {
		return this.taskMapper.selectByTaskid(id);
	}

	@Override
	public int selectTodayTaskCount(Map<String, Object> map) throws Exception {
		return this.taskMapper.selectTodayTaskCount(map);
	}

	/**
	 * 查询工会的今日任务
	 *
	 * @param map
	 * @return
	 * @throws Exception
	 */
	@Override
	public int tradeTodayTaskCount(Map<String, Object> map) throws Exception {
		return this.taskMapper.tradeTodayTaskCount(map);
	}

	@Override
	public List<Map<String, Object>> getTaskLineChar(Map<String, Object> map) throws Exception {
		return this.taskMapper.getTaskLineChar(map);
	}

	@Override
	public List<Map<String, Object>> getTaskLineWeekAndMonth(Map<String, Object> map) throws Exception {
		return this.taskMapper.getTaskLineWeekAndMonth(map);
	}

	/**
	 * 图形数据_日数据_完成状态
	 *
	 * @param map
	 * @return
	 * @throws Exception
	 */
	@Override
	public List<Map<String, Object>> countTaskFinishState(Map<String, Object> map) throws Exception {
		return this.taskMapper.countTaskFinishState(map);
	}

	/**
	 * 图形数据_日数据_未完成状态
	 *
	 * @param map
	 * @return
	 * @throws Exception
	 */
	@Override
	public List<Map<String, Object>> countTaskUnFinishState(Map<String, Object> map) throws Exception {
		return this.taskMapper.countTaskUnFinishState(map);
	}

	/**
	 * 图形数据_日数据_逾期状态
	 *
	 * @param map
	 * @return
	 * @throws Exception
	 */
	@Override
	public List<Map<String, Object>> countTaskOverState(Map<String, Object> map) throws Exception {
		return this.taskMapper.countTaskOverState(map);
	}

	/**
	 * 完成率 24小时统计
	 *
	 * @param map
	 * @return
	 * @throws Exception
	 */
	@Override
	public Map<String, Object> getTaskHourStat(Map<String, Object> map) throws Exception {
		List<Map<String, Object>> taskLineChar = new ArrayList<>();
		Map<String, Object> statMap = new HashMap<>();
		int state = (int) map.get("state");
		// 完成
		if (state == 2) {
			taskLineChar = this.countTaskFinishState(map);// 查询数据库统计返回数据
		}
		// 未完成
		if (state == 1) {
			taskLineChar = this.countTaskUnFinishState(map);// 查询数据库统计返回数据
		}
		// 预期
		if (state == 3) {
			taskLineChar = this.countTaskOverState(map);// 查询数据库统计返回数据
		}
		List<Map<String, Object>> rsList = new ArrayList<>();

		int totalCount = 0;// 总数计算
		int maxTaskNum = 0;// 任务的最大值
		for (int i = 0; i < 24; i++) {
			Map<String, Object> tempMap = new HashMap<>();
			tempMap.put("xAxis", i);
			tempMap.put("yAxis", 0);// 初始化赋值
			for (int k = 0; k < taskLineChar.size(); k++) {
				Map<String, Object> map1 = taskLineChar.get(k);
				Object hour_time = map1.get("xAxis");
				if (hour_time == null) {
					break;
				} else {
					Object yAxis = map1.get("yAxis");
					int hourTime = Integer.parseInt((String) hour_time);
					if (i == hourTime) {
						int task_count = 0;
						if (yAxis instanceof Long) {
							task_count = new Long((Long) yAxis).intValue();
						}
						totalCount += task_count;// 统计总数
						// 找出最大值
						if (maxTaskNum < task_count) {
							maxTaskNum = task_count;
						}
						tempMap.put("yAxis", yAxis);
						break;
					}
				}
			}
			rsList.add(tempMap);
		}
		statMap.put("totalCount", totalCount);
		statMap.put("maxTaskNum", maxTaskNum);
		statMap.put("statList", rsList);
		return statMap;
	}

	/**
	 * 业务员/主播任务小时维度统计
	 *
	 * @param map
	 * @return
	 * @throws Exception
	 */
	@Override
	public Map<String, Object> getTaskHourStatByAnchorAndSaleMan(Map<String, Object> map, UserInfo userInfo) throws Exception {

		List<Map<String, Object>> taskLineChar = new ArrayList<>();
		List<String> userIdList = this.userIdList(userInfo);
		map.put("userIdList", userIdList);
		int state = (int) map.get("state");
		// 完成
		if (state == 2) {
			taskLineChar = this.countTaskByDeptFinishState(map);
		}
		// 预期
		if (state == 3) {
			taskLineChar = this.countTaskByDeptOverState(map);
		}
		return nowDayHoursCount(taskLineChar);
	}

	/**
	 * 周统计
	 *
	 * @param weekmap
	 * @param date
	 * @return
	 * @throws Exception
	 */
	@Override
	public Map<String, Object> getTaskWeekStat(Map<String, Object> weekmap, Date date) throws Exception {
		Map<String, Object> statMap = new HashMap<>();
		List<Map<String, Object>> weektaskList = new ArrayList<>();
		int start = (int) weekmap.get("state");
		// 完成
		if (start == 2) {
			weektaskList = this.taskMapper.countTaskFinishStateWeekAndMonth(weekmap);
		}
		// 未完成
		if (start == 1) {
			weektaskList = this.taskMapper.countTaskUnFinishStateWeekAndMonth(weekmap);
		}
		// 逾期
		if (start == 3) {
			weektaskList = this.taskMapper.countTaskOverStateWeekAndMonth(weekmap);
		}
		List<Map<String, Object>> weekMap = new ArrayList<>();
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(DataUtil.getCurrentFirstDayOrLastWeekFirstDay(new Date()));
		calendar.add(Calendar.DATE, -1);
		for (int i = 0; i < 7; i++) {
			Map<String, Object> map = new HashMap<>();
			calendar.add(Calendar.DATE, 1);// 日期自增
			map.put("xAxis", dateFormat.format(calendar.getTime()));
			map.put("yAxis", 0);// 初始化赋值
			weekMap.add(map);
		}
		int weektotalCount = 0;
		int weekmaxTaskNum = 0;
		for (int i = 0; i < weekMap.size(); i++) {
			Map<String, Object> map = weekMap.get(i);
			String date_time = (String) map.get("xAxis");
			for (int i1 = 0; i1 < weektaskList.size(); i1++) {
				Map<String, Object> map1 = weektaskList.get(i1);
				String date_time1 = (String) map1.get("xAxis");
				if (date_time1.equals(date_time)) {
					weekMap.set(i, map1);
					// Object count = map.get("yAxis");
					Object param = map1.get("yAxis");
					int count = 0;
					if (param instanceof Long) {
						count = ((Long) param).intValue();
					}
					weektotalCount += (int) count;
					if ((int) count > weekmaxTaskNum) { // 本周最大值
						weekmaxTaskNum = (int) count;
					}
					break;
				}
			}

		}
		statMap.put("weektotalCount", weektotalCount);
		statMap.put("weekmaxTaskNum", weekmaxTaskNum);
		statMap.put("weekMap", weekMap);
		return statMap;
	}

	/**
	 * 主播/业务员 按任务周维度统计
	 *
	 * @param weekmap
	 * @return
	 * @throws Exception
	 */
	@Override
	public Map<String, Object> getTaskWeekStatToSaleManOrAnchor(Map<String, Object> weekmap, UserInfo userInfo) throws Exception {
		List<Map<String, Object>> weektaskList = new ArrayList<>();
		int start = (int) weekmap.get("state");
		List<String> userIdList = this.userIdList(userInfo);
		weekmap.put("userIdList", userIdList);
		// 完成
		if (start == 2) {
			weektaskList = this.taskMapper.countTaskByDeptFinishStateWeekOrMonth(weekmap);
		}
		// 逾期
		if (start == 3) {
			weektaskList = this.taskMapper.countTaskByDeptOverStateWeekOrMonth(weekmap);
		}
		return nowWeekCount(weektaskList);
	}

	/**
	 * 图形数据_周_月统计_完成状态
	 *
	 * @param map
	 * @return
	 * @throws Exception
	 */
	@Override
	public List<Map<String, Object>> countTaskFinishStateWeekAndMonth(Map<String, Object> map) throws Exception {
		return this.taskMapper.countTaskFinishStateWeekAndMonth(map);
	}

	/**
	 * 图形数据_周_月统计_未完成状态
	 *
	 * @param map
	 * @return
	 * @throws Exception
	 */
	@Override
	public List<Map<String, Object>> countTaskUnFinishStateWeekAndMonth(Map<String, Object> map) throws Exception {
		return this.taskMapper.countTaskUnFinishStateWeekAndMonth(map);
	}

	/**
	 * 图形数据_周_月统计_逾期状态
	 *
	 * @param map
	 * @return
	 * @throws Exception
	 */
	@Override
	public List<Map<String, Object>> countTaskOverStateWeekAndMonth(Map<String, Object> map) throws Exception {
		return this.taskMapper.countTaskOverStateWeekAndMonth(map);
	}

	/**
	 * 月统计
	 *
	 * @param monthmap
	 * @param startdate
	 * @param enddate
	 * @return
	 * @throws Exception
	 */
	@Override
	public Map<String, Object> getTaskMonthStat(Map<String, Object> monthmap, Date startdate, Date enddate) throws Exception {
		Map<String, Object> statMap = new HashMap<>();
		List<Map<String, Object>> monthtaskfinishList = new ArrayList<>();
		int state = (int) monthmap.get("state");
		// 完成
		if (state == 2) {
			monthtaskfinishList = this.taskMapper.countTaskFinishStateWeekAndMonth(monthmap);
		}
		// 未完成
		if (state == 1) {
			monthtaskfinishList = this.taskMapper.countTaskUnFinishStateWeekAndMonth(monthmap);
		}
		// 逾期
		if (state == 3) {
			monthtaskfinishList = this.taskMapper.countTaskOverStateWeekAndMonth(monthmap);
		}
		List<Map<String, Object>> monthMap = new ArrayList<>();
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(startdate);
		calendar.add(Calendar.DATE, -1);
		for (int i = 0; i < 32; i++) {
			Map<String, Object> map = new HashMap<>();
			calendar.add(Calendar.DATE, 1);// 日期自增
			map.put("xAxis", dateFormat.format(calendar.getTime()));
			map.put("yAxis", 0);// 初始化赋值
			monthMap.add(map);
			if (dateFormat.format(calendar.getTime()).equals(dateFormat.format(enddate))) {
				break;
			}
		}
		int monthtotalCount = 0;
		int monthmaxTaskNum = 0;
		for (int i = 0; i < monthMap.size(); i++) {
			Map<String, Object> map = monthMap.get(i);
			String date_time = (String) map.get("xAxis");
			for (int i1 = 0; i1 < monthtaskfinishList.size(); i1++) {
				Map<String, Object> map1 = monthtaskfinishList.get(i1);
				String date_time1 = (String) map1.get("xAxis");
				if (date_time1.equals(date_time)) {
					monthMap.set(i, map1);
					Object param = map1.get("yAxis");
					int count = 0;
					if (param instanceof Long) {
						count = ((Long) param).intValue();
					}
					monthtotalCount += (int) count;
					if ((int) count > monthmaxTaskNum) { // 本周最大值
						monthmaxTaskNum = (int) count;
					}
					break;
				}
			}

		}
		statMap.put("monthtotalCount", monthtotalCount);
		statMap.put("monthmaxTaskNum", monthmaxTaskNum);
		statMap.put("monthMap", monthMap);
		return statMap;
	}

	/**
	 * 业务员/主播 统计任务月维度统计
	 *
	 * @param monthmap
	 * @return
	 * @throws Exception
	 */
	@Override
	public Map<String, Object> getTaskMonthStatToSaleManOrAnchor(Map<String, Object> monthmap, Date startdate, Date enddate, UserInfo userInfo) throws Exception {
		List<Map<String, Object>> monthtaskfinishList = new ArrayList<>();
		int state = (int) monthmap.get("state");
		List<String> userIdList = this.userIdList(userInfo);
		monthmap.put("userIdList", userIdList);
		// 完成
		if (state == 2) {
			monthtaskfinishList = this.taskMapper.countTaskByDeptFinishStateWeekOrMonth(monthmap);// 业务员
		}
		// 逾期
		if (state == 3) {
			monthtaskfinishList = this.taskMapper.countTaskByDeptOverStateWeekOrMonth(monthmap);
		}
		return nowMonthCount(monthtaskfinishList, startdate, enddate);
	}

	/**
	 * 业务员/主播任务完成情况图形数据_日统计_完成状态
	 *
	 * @param map
	 * @return
	 * @throws Exception
	 */
	@Override
	public List<Map<String, Object>> countTaskByDeptFinishState(Map<String, Object> map) throws Exception {
		return this.taskMapper.countTaskByDeptFinishState(map);
	}

	/**
	 * 业务员/主播任务完成情况图形数据_日统计_逾期状态
	 *
	 * @param map
	 * @return
	 * @throws Exception
	 */
	@Override
	public List<Map<String, Object>> countTaskByDeptOverState(Map<String, Object> map) throws Exception {
		return this.taskMapper.countTaskByDeptOverState(map);
	}

	@Override
	public List<TaskRankVO> selectRankList(Map<String, Object> params) throws Exception {
		return this.taskMapper.selectRankList(params);
	}

	@Override
	public TaskRankVO selectmyRankList(Map<String, Object> params) throws Exception {
		return this.taskMapper.selectmyRankList(params);
	}

	@Override
	public int owTotalData(Map<String, Object> params) throws Exception {
		return this.taskMapper.owTotalData(params);
	}

	/**
	 * 工会业务员完成率统计
	 *
	 * @param map
	 * @return
	 * @throws Exception
	 */
	@Override
	public List<Map<String, Integer>> getTaskLineToSaler(Map<String, Object> map) throws Exception {
		return this.taskMapper.getTaskLineToSaler(map);
	}

	/**
	 * 开放平台工会任务看板数据
	 *
	 * @param map
	 * @return
	 * @throws Exception
	 */
	@Override
	public List<Map<String, Object>> tradeUnionDataLine(Map<String, Object> map, Dept dept) throws Exception {
		List<Map<String, Object>> resultList = new ArrayList<>();
		List<Dept> deptList = this.deptMapper.selectList(dept);
		// 体系下所有子节点
		if (deptList != null && deptList.size() > 0) {
			for (Dept deptCode : deptList) {
				List<String> deptIdList = new ArrayList<>();
				this.selectDeptSon(deptCode.getCode(), deptIdList);
				// 查询用户
				List<String> userIdList = new ArrayList<>();
				if (dept.getSourceSys() == 1) { // 主播
					userIdList = this.userInfoMapper.selectAnchorIdsByDeptIds(deptIdList);
				} else {
					userIdList = this.userInfoMapper.selectSalesmanUserIdsByDeptIds(deptIdList);
				}
				map.put("userIdList", userIdList);
				int taskCount = this.taskMapper.countTradeUnionTaskByState(map);
				Map<String, Object> objectMap = new HashMap<>();
				objectMap.put("xAxis", deptCode.getName());
				objectMap.put("yAxis", taskCount);
				resultList.add(objectMap);
			}
		}
		return resultList;
	}

	/**
	 * 开放平台工会任务情况数据
	 *
	 * @param map
	 * @return
	 * @throws Exception
	 */
	@Override
	public int countTradeUnionTaskByState(Map<String, Object> map) throws Exception {
		return this.taskMapper.countTradeUnionTaskByState(map);
	}

	/**
	 * 业务员/主播任务完成情况图形数据_周月统计_完成状态
	 *
	 * @param map
	 * @return
	 * @throws Exception
	 */
	@Override
	public List<Map<String, Object>> countTaskByDeptFinishStateWeekOrMonth(Map<String, Object> map) throws Exception {
		return this.taskMapper.countTaskByDeptFinishStateWeekOrMonth(map);
	}

	/**
	 * 业务员/主播任务完成情况图形数据_周月统计_逾期状态
	 *
	 * @param map
	 * @return
	 * @throws Exception
	 */
	@Override
	public List<Map<String, Object>> countTaskByDeptOverStateWeekOrMonth(Map<String, Object> map) throws Exception {
		return this.taskMapper.countTaskByDeptOverStateWeekOrMonth(map);
	}

	/**
	 * 统计今天24小时数据
	 *
	 * @param taskLineChar
	 * @return
	 */
	public Map<String, Object> nowDayHoursCount(List<Map<String, Object>> taskLineChar) {

		Map<String, Object> statMap = new HashMap<>();
		List<Map<String, Object>> rsList = new ArrayList<>();
		int totalCount = 0;// 总数计算
		int maxTaskNum = 0;// 任务的最大值
		for (int i = 0; i < 24; i++) {
			Map<String, Object> tempMap = new HashMap<>();
			tempMap.put("xAxis", i);
			tempMap.put("yAxis", 0);// 初始化赋值
			for (int k = 0; k < taskLineChar.size(); k++) {
				Map<String, Object> map1 = taskLineChar.get(k);
				Object hour_time = map1.get("xAxis");
				if (hour_time == null) {
					break;
				} else {
					Object yAxis = map1.get("yAxis");
					int hourTime = Integer.parseInt((String) hour_time);
					if (i == hourTime) {
						int task_count = 0;
						if (yAxis instanceof Long) {
							task_count = new Long((Long) yAxis).intValue();
						}
						totalCount += task_count;// 统计总数
						// 找出最大值
						if (maxTaskNum < task_count) {
							maxTaskNum = task_count;
						}
						tempMap.put("yAxis", yAxis);
						break;
					}
				}
			}
			rsList.add(tempMap);
		}
		statMap.put("totalCount", totalCount);
		statMap.put("maxTaskNum", maxTaskNum);
		statMap.put("statList", rsList);
		return statMap;
	}

	/**
	 * 自然周统计
	 *
	 * @param taskLineChar
	 * @return
	 */
	public Map<String, Object> nowWeekCount(List<Map<String, Object>> taskLineChar) {
		List<Map<String, Object>> weekMap = new ArrayList<>();
		Map<String, Object> statMap = new HashMap<>();
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(DataUtil.getCurrentFirstDayOrLastWeekFirstDay(new Date()));
		calendar.add(Calendar.DATE, -1);
		for (int i = 0; i < 7; i++) {
			Map<String, Object> map = new HashMap<>();
			calendar.add(Calendar.DATE, 1);// 日期自增
			map.put("xAxis", dateFormat.format(calendar.getTime()));
			map.put("yAxis", 0);// 初始化赋值
			weekMap.add(map);
		}
		int weektotalCount = 0;
		int weekmaxTaskNum = 0;
		for (int i = 0; i < weekMap.size(); i++) {
			Map<String, Object> map = weekMap.get(i);
			String date_time = (String) map.get("xAxis");
			for (int i1 = 0; i1 < taskLineChar.size(); i1++) {
				Map<String, Object> map1 = taskLineChar.get(i1);
				String date_time1 = (String) map1.get("xAxis");
				if (date_time1.equals(date_time)) {
					weekMap.set(i, map1);
					Object param = map1.get("yAxis");
					int count = 0;
					if (param instanceof Long) {
						count = ((Long) param).intValue();
					}
					weektotalCount += (int) count;
					if ((int) count > weekmaxTaskNum) { // 本周最大值
						weekmaxTaskNum = (int) count;
					}
					break;
				}
			}

		}
		statMap.put("weektotalCount", weektotalCount);
		statMap.put("weekmaxTaskNum", weekmaxTaskNum);
		statMap.put("weekMap", weekMap);
		return statMap;
	}

	/**
	 * 自然月统计
	 *
	 * @param taskLineChar
	 * @param startdate
	 * @param enddate
	 * @return
	 */
	public Map<String, Object> nowMonthCount(List<Map<String, Object>> taskLineChar, Date startdate, Date enddate) {
		Map<String, Object> statMap = new HashMap<>();
		List<Map<String, Object>> monthMap = new ArrayList<>();
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(startdate);
		calendar.add(Calendar.DATE, -1);
		for (int i = 0; i < 32; i++) {
			Map<String, Object> map = new HashMap<>();
			calendar.add(Calendar.DATE, 1);// 日期自增
			map.put("xAxis", dateFormat.format(calendar.getTime()));
			map.put("yAxis", 0);// 初始化赋值
			monthMap.add(map);
			if (dateFormat.format(calendar.getTime()).equals(dateFormat.format(enddate))) {
				break;
			}
		}
		int monthtotalCount = 0;
		int monthmaxTaskNum = 0;
		for (int i = 0; i < monthMap.size(); i++) {
			Map<String, Object> map = monthMap.get(i);
			String date_time = (String) map.get("xAxis");
			for (int i1 = 0; i1 < taskLineChar.size(); i1++) {
				Map<String, Object> map1 = taskLineChar.get(i1);
				String date_time1 = (String) map1.get("xAxis");
				if (date_time1.equals(date_time)) {
					monthMap.set(i, map1);
					Object param = map1.get("yAxis");
					int count = 0;
					if (param instanceof Long) {
						count = ((Long) param).intValue();
					}
					monthtotalCount += (int) count;
					if ((int) count > monthmaxTaskNum) { // 本周最大值
						monthmaxTaskNum = (int) count;
					}
					break;
				}
			}

		}
		statMap.put("monthtotalCount", monthtotalCount);
		statMap.put("monthmaxTaskNum", monthmaxTaskNum);
		statMap.put("monthMap", monthMap);
		return statMap;
	}

	/**
	 * 开放平台统计家族/工会体系任务
	 *
	 * @param type
	 * @param dept
	 * @return
	 * @throws Exception
	 */
	@Override
	public Map<String, Object> countSystemBytypeAndDept(int type, Dept dept) throws Exception {
		Map<String, Object> resultMap = new HashMap<>();
		Map<String, Object> map = new HashMap<>();
		Map<String, Object> mapFinishState = new HashMap<>();
		Map<String, Object> mapUnFinishState = new HashMap<>();
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
		if (type == 1) {
			map.put("startTime", dateFormat.format(DataUtil.getStartTime()));
			map.put("endTime", dateFormat.format(DataUtil.getnowEndTime()));
			map.put("state", 3);
			// 逾期
			List<Map<String, Object>> overdueList = this.tradeUnionDataLine(map, dept);
			// 未完成
			mapUnFinishState.put("unFinishStartTime", dateFormat.format(DataUtil.getStartTime()));
			mapUnFinishState.put("unFinishEndTime", dateFormat.format(DataUtil.getnowEndTime()));
			mapUnFinishState.put("state", 1);
			List<Map<String, Object>> unFinishList = this.tradeUnionDataLine(mapUnFinishState, dept);
			// 完成
			mapFinishState.put("finishStartTime", dateFormat.format(DataUtil.getStartTime()));
			mapFinishState.put("finishEndTime", dateFormat.format(DataUtil.getnowEndTime()));
			mapFinishState.put("state", 2);
			List<Map<String, Object>> finishList = this.tradeUnionDataLine(mapFinishState, dept);
			resultMap.put("overdueList", overdueList);
			resultMap.put("unFinishList", unFinishList);
			resultMap.put("finishList", finishList);
		}
		if (type == 2) {
			String startTime = dateFormat.format(DataUtil.getCurrentFirstDayOrLastWeekFirstDay(new Date()));
			String endTime = dateFormat.format(DataUtil.getnowEndTime());
			map.put("startTime", startTime);
			map.put("endTime", endTime);
			map.put("state", 3);
			// 逾期
			List<Map<String, Object>> overdueList = this.tradeUnionDataLine(map, dept);
			// 未完成
			mapUnFinishState.put("unFinishStartTime", startTime);
			mapUnFinishState.put("unFinishEndTime", endTime);
			mapUnFinishState.put("state", 1);
			List<Map<String, Object>> unFinishList = this.tradeUnionDataLine(mapUnFinishState, dept);
			// 完成
			mapFinishState.put("finishStartTime", startTime);
			mapFinishState.put("finishEndTime", endTime);
			mapFinishState.put("state", 2);
			List<Map<String, Object>> finishList = this.tradeUnionDataLine(mapFinishState, dept);
			resultMap.put("overdueList", overdueList);
			resultMap.put("unFinishList", unFinishList);
			resultMap.put("finishList", finishList);
		}
		if (type == 3) {
			String startTime = dateFormat.format(DataUtil.getCurrentMonthDateBegin(new Date()));
			String endTime = dateFormat.format(DataUtil.getnowEndTime());
			map.put("startTime", startTime);
			map.put("endTime", endTime);
			map.put("state", 3);
			// 逾期
			List<Map<String, Object>> overdueList = this.tradeUnionDataLine(map, dept);
			// 未完成
			mapUnFinishState.put("unFinishStartTime", startTime);
			mapUnFinishState.put("unFinishEndTime", endTime);
			mapUnFinishState.put("state", 1);
			List<Map<String, Object>> unFinishList = this.tradeUnionDataLine(mapUnFinishState, dept);
			// 完成
			mapFinishState.put("finishStartTime", startTime);
			mapFinishState.put("finishEndTime", endTime);
			mapFinishState.put("state", 2);
			List<Map<String, Object>> finishList = this.tradeUnionDataLine(mapFinishState, dept);
			resultMap.put("overdueList", overdueList);
			resultMap.put("unFinishList", unFinishList);
			resultMap.put("finishList", finishList);
		}
		return resultMap;
	}

	/**
	 * 统计 我的 家族 工会 今日任务
	 *
	 * @return
	 * @throws Exception
	 */
	@Override
	public Map<String, Integer> countMyTaskNum(int type, UserInfo userInfo) throws Exception {
		Map<String, Integer> resultmap = new HashMap<>();
		SimpleDateFormat dateFormatDay = new SimpleDateFormat("yyyy-MM-dd");
		Map<String, Object> paramMap = new HashMap<>();
		Map<String, Object> paramMap2 = new HashMap<>();
		Map<String, Object> paramMap3 = new HashMap<>();
		if (type == 1) {// 我的任务 业务员、主播用户类型
			paramMap.put("userId", userInfo.getId());
			paramMap.put("prority", 2);
			int counturgenct = this.selectTodayTaskCount(paramMap);// 获取我的紧急任务总数
			paramMap2.put("userId", userInfo.getId());
			paramMap2.put("state", 3);
			int countoverdutask = this.selectTodayTaskCount(paramMap2);// 获取我的逾期任务总数
			paramMap2.put("state", 2);
			int countfinish = this.selectTodayTaskCount(paramMap2);// 获取已完成任务总数
			paramMap3.put("userId", userInfo.getId());
			paramMap3.put("startTime", dateFormatDay.format(new Date()));
			int count = this.selectTodayTaskCount(paramMap3);// 获取我的今天任务总数
			resultmap.put("count", count);
			resultmap.put("counturgenct", counturgenct);
			resultmap.put("countoverdutask", countoverdutask);
			resultmap.put("countfinish", countfinish);
		} else { // 我的、工会家族发布的任务
			Dept dept = this.deptMapper.selectByPrimaryKey(userInfo.getDeptId());
			List<String> deptIdList = new ArrayList<>();
			if ((dept.getSourceSys() == 2 && dept.getType() == 5) || (dept.getSourceSys() == 1 && dept.getType() == 3)) { // 小组
				deptIdList.add(dept.getId());
			} else {
				this.selectDeptSon(dept.getCode(), deptIdList);
			}
			if (type == 2) { // 工会家族发布
				// Dept topDept = this.deptMapper.selectByPrimaryKey(userInfo.getDeptId());
				// 查询体系
				/*
				 * Dept selectTopDept = this.selectTopDept(dept.getCode()); if(selectTopDept != null){ this.selectDeptSon(selectTopDept.getCode(),deptIdList); if(selectTopDept.getType() == 1){ deptIdList.add(selectTopDept.getId()); } }
				 */
				List<String> userIdList = new ArrayList<>();
				if (userInfo.getSourceSys() == 1) {
					userIdList = this.userInfoMapper.selectAnchorIdsByDeptIds(deptIdList);
				} else {
					userIdList = this.userInfoMapper.selectSalesmanUserIdsByDeptIds(deptIdList);
				}
				// userIdList.add(userInfo.getId());
				paramMap.put("userIdList", userIdList);
				paramMap2.put("userIdList", userIdList);
				paramMap3.put("userIdList", userIdList);
			} else { // 我发布的
				paramMap.put("type", type);
				paramMap.put("userId", userInfo.getId());
				paramMap2.put("type", type);
				paramMap2.put("userId", userInfo.getId());
				paramMap3.put("type", type);
				paramMap3.put("userId", userInfo.getId());
			}

			// 工会下的用户
			// paramMap.put("nowTime", dateFormatDay.format(new Date()));//逾期
			paramMap.put("state", 3);
			int countoverdutask = this.tradePublishTaskCount(paramMap);
			paramMap.put("state", 2);
			int countfinishtask = this.tradePublishTaskCount(paramMap);
			paramMap2.put("prority", 2);// 紧急
			int counturgenct = this.tradePublishTaskCount(paramMap2);
			paramMap3.put("startTime", dateFormatDay.format(new Date()));
			int count = this.tradePublishTaskCount(paramMap3);

			resultmap.put("countoverdutask", countoverdutask);
			resultmap.put("countfinish", countfinishtask);
			resultmap.put("counturgenct", counturgenct);
			resultmap.put("count", count);
		}
		return resultmap;
	}

	/**
	 * 查询我/工会/家族的发布任务数量
	 *
	 * @param map
	 * @return
	 * @throws Exception
	 */
	@Override
	public int tradePublishTaskCount(Map<String, Object> map) throws Exception {
		return this.taskMapper.tradePublishTaskCount(map);
	}

	/**
	 * 新员工添加培训任务(定时任务)
	 *
	 * @param type
	 * @return
	 * @throws Exception
	 */
	@Override
	public List<Task> selectNewUserTrainTaskJobList(int type, String tenantCode) throws Exception {
		if (StringUtils.isNotEmpty(tenantCode)) {
			TenantCodeUtil.getInstance().createServerTenantCode(tenantCode);
		}
		return this.selectNewUserTrainTaskList(type);
	}

	/**
	 * 新员工添加培训任务
	 * @param type
	 * @return
	 * @throws Exception
	 */
	@Override
	public List<Task> selectNewUserTrainTaskList(int type) throws Exception {
		return this.taskMapper.selectNewUserTrainTaskJobList(type);
	}

	/**
	 * 查询推广任务
	 * @param state
	 * @return
	 * @throws Exception
	 */
	@Override
	public List<Task> selectPromoteTaskJobList(int state) throws Exception {
		return this.taskMapper.selectPromoteTaskJobList(state);
	}

	@Override
	public List<Task> selectPromoteTaskJobListTenantCode(int state, String tenantCode) throws Exception {
		if (StringUtils.isNotEmpty(tenantCode)) {
			TenantCodeUtil.getInstance().createServerTenantCode(tenantCode);
		}
		return this.selectPromoteTaskJobList(state);
	}

	/**
	 * 新增维护任务
	 * @param tenantCode
	 * @return
	 * @throws Exception
	 */
	public int insertMaintainTask(String tenantCode) throws Exception{
		if (StringUtils.isNotEmpty(tenantCode)) {
			TenantCodeUtil.getInstance().createServerTenantCode(tenantCode);
		}
		ParameterConfigure queryParam = this.parameterConfigureMapper.selectByCode("MAINTAIN_TASK_CUMULATIVE_RECHARGE_TYPE");
		if (queryParam != null) {
			List<ParameterConfigure> parameterConfigureList = this.parameterConfigureMapper.selectListByParentId(queryParam.getId());
			if (parameterConfigureList.size() > 0) {
				UserInfo query = new UserInfo();
				query.setType(11);
				query.setSourceSys(1);
				List<UserInfo> userInfoList = this.userInfoMapper.selectList(query);
				for (UserInfo userInfo : userInfoList) {

					// 查询玩家的消费金额
					List<Map<String,Object>> playerAmountList = new ArrayList<>();
					if(StringUtils.isNotBlank(userInfo.getOtherAccount())){
						playerAmountList = this.playerRelateConsumeMapper.selectPlayerAmount(userInfo.getOtherAccount());
					}

					for (Map<String,Object> playerMap: playerAmountList) {
						BigDecimal amount = (BigDecimal)playerMap.get("amount");
						String playerId = (String)playerMap.get("playerId");
						for (ParameterConfigure parameterConfigure : parameterConfigureList) {
							if (amount.compareTo(new BigDecimal(parameterConfigure.getValue())) >= 0) {
								Player player = this.playerMapper.selectByPlayerId(playerId);
								if(player!=null) {
									Calendar date = Calendar.getInstance();
									date.setTime(new Date());
									// 新增任务
									TaskVO task = new TaskVO();
									task.setId(PrimaryKeyGeneratorUtil.getInstance().getRandomKey());
									task.setName(parameterConfigure.getName()+"维护任务");
									task.setPrority(0);
									task.setBeginTime(date.getTime());
									date.add(Calendar.DATE,1);
									task.setEndTime(date.getTime());
									task.setType(1);
									task.setUserType(1);

									List<TaskRelateAssignPerson> taskRelateAssignPersonList = new ArrayList<>();
									List<TaskRelateMaintainUser> taskRelateMaintainUserList = new ArrayList<>();
									TaskRelateMaintainUser taskRelateMaintainUser = new TaskRelateMaintainUser();
									TaskRelateAssignPerson taskRelateAssignPerson = new TaskRelateAssignPerson();
									taskRelateAssignPerson.setAccount(userInfo.getAccount());
									taskRelateAssignPerson.setName(userInfo.getName());
									taskRelateAssignPerson.setUserId(userInfo.getId());

									taskRelateMaintainUser.setAnchorId(userInfo.getOtherAccount());
									taskRelateMaintainUser.setName(player.getNickName());
									taskRelateMaintainUser.setNickName(player.getNickName());
									taskRelateMaintainUser.setUserId(playerId);
									taskRelateAssignPersonList.add(taskRelateAssignPerson);
									taskRelateMaintainUserList.add(taskRelateMaintainUser);
									task.setTaskRelateAssignPersonList(taskRelateAssignPersonList);
									task.setTaskRelateMaintainUserList(taskRelateMaintainUserList);

									Map<String,Object> map = new HashMap<>();
									map.put("userId", userInfo.getId());
									map.put("playerId",playerId);
									map.put("taskName",task.getName());
									if(this.taskMapper.selectMaintainTaskExist(map)==null){
										this.insertSelectiveByTaskVOAndUserInfo(task, userInfo);
									}
									break;
								}
							}
						}
					}
				}
				
			}
		}
		return 1;
	}


	/**
	 * 查询所有的子集id
	 *
	 * @param parentCode
	 * @param list
	 * @throws Exception
	 */
	private void selectDeptSon(String parentCode, List<String> list) throws Exception {
		List<Dept> deptList = this.deptMapper.selectByParentCode(parentCode);
		if (deptList != null) {
			for (Dept dept1 : deptList) {
				list.add(dept1.getId());
				selectDeptSon(dept1.getCode(), list);
			}
		}
	}

	/**
	 * 递归查找部门的顶级
	 *
	 * @return
	 */
	private Dept selectTopDept(String code) throws Exception {
		Dept dept = this.deptMapper.selectByCode(code);
		if (dept.getType() == 1) {
			return dept;
		} else {
			return selectTopDept(dept.getParentCode());
		}
	}

	/**
	 * 查询用户体系用户
	 *
	 * @param userInfo
	 * @return
	 * @throws Exception
	 */
	private List<String> userIdList(UserInfo userInfo) throws Exception {
		List<String> userIdList = new ArrayList<>();
		List<String> deptIdList = new ArrayList<>();
		List<Map<String, Object>> taskLineChar = new ArrayList<>();
		if(userInfo==null)
		{
			return userIdList;
		}
		Dept dept = this.deptMapper.selectByPrimaryKey(userInfo.getDeptId());
		if (dept != null) {
			if ((userInfo.getSourceSys() == 1 && userInfo.getType() == 3) || (userInfo.getSourceSys() == 2 && userInfo.getType() == 5)) { // 小组
				deptIdList.add(userInfo.getDeptId());
			} else {
				this.selectDeptSon(dept.getCode(), deptIdList);
			}
		}
		if (userInfo.getSourceSys() == 2) {
			userIdList = this.userInfoMapper.selectAnchorIdsByDeptIds(deptIdList);
		} else {
			userIdList = this.userInfoMapper.selectSalesmanUserIdsByDeptIds(deptIdList);
		}
		return userIdList;
	}

}
